home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Language/OS - Multiplatform Resource Library
/
LANGUAGE OS.iso
/
simula
/
books
/
books.lha
/
kirkerud
/
binsearchtest.sim
< prev
next >
Wrap
Text File
|
1993-08-16
|
2KB
|
58 lines
begin
procedure Binary_search_in_table(table, low_bound, high_bound,
search_value, value_found, index_of_value);
name value_found, index_of_value;
integer array table;
integer low_bound, high_bound, search_value, index_of_value;
Boolean value_found;
if low_bound > high_bound or
search_value < table(low_bound) or
search_value > table(high_bound)
then value_found := false else
begin integer middle;
while low_bound + 1 < high_bound do
begin
! At this place it is always the case that
! table(low_bound) <= search_value <= table(high_bound);
middle := (low_bound + high_bound)//2;
if table(middle) <= search_value
then low_bound := middle
else high_bound := middle;
end;
! At this place it is always the case that
! 1: table(low_bound) <= search_value <= table(high_bound);
! 2: Either: low_bound + 1 = high_bound;
! or: low_bound = high_bound;
if search_value = table(high_bound) then
begin value_found := true; index_of_value := high_bound end else
if search_value = table(low_bound) then
begin value_found := true; index_of_value := low_bound end
else value_found := false;
end of Binary_search_in_table;
integer array a(1:1000);
integer ind;
procedure bintest(val); integer val;
begin
Boolean found; integer index;
Binary_search_in_table(a, 1, 1000, val, found, index);
outtext("The value "); outint(val, 0);
if found then begin outtext(" was found at index "); outint(index, 0) end
else outtext(" was not found");
outimage;
end;
for ind := 1 step 1 until 1000 do a(ind) := 10*ind;
bintest(100);
bintest(1000);
bintest(10);
bintest(10000);
bintest(10010);
bintest(0);
end